//
//  SYLJEmoticon.swift
//  Emoticon
//
//  Created by 刘俊 on 15/10/24.
//  Copyright © 2015年 刘俊. All rights reserved.
//

import UIKit

/// 可重用标识符号
private let EmoticonViewCellId = "EmoticonViewCellId"

/// 表情键盘视图
class SYLJEmoticon: UIView {

    /// 回调属性
    private var selectedEmoticonCallBack: (emoticon: Emoticon)->()
    //MARK: - 监听方法
    @objc private func clickItem(item: UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    //MARK: - 构造函数
    init(selectedEmoticon: (emoticon: Emoticon)->()) {
        selectedEmoticonCallBack = selectedEmoticon
        
        var rect = UIScreen.mainScreen().bounds
        //        rect.height = 216 // 在程序开发中英文键盘默认高度为216,中文键盘默认为258
        rect.size.height = 216
        super.init(frame: rect)
        
        setupUI()
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }

    }
//    override init(frame: CGRect) {
//        var rect = UIScreen.mainScreen().bounds
////        rect.height = 216 // 在程序开发中英文键盘默认高度为216,中文键盘默认为258
//        rect.size.height = 216
//        super.init(frame: rect)
//        
//        setupUI()
//        dispatch_async(dispatch_get_main_queue()) { () -> Void in
//            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
//            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
//        }
//    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 懒加载控件
    /// 表情集合视图
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonViewLayout())
    /// 工具栏
    private lazy var toolbar: UIToolbar = UIToolbar()
    ///模型数据
    let packages = EmoticonViewManger.shardManger.packages
    
    //MARK: - 表情键盘视图布局
    private class EmoticonViewLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            super.prepareLayout()
            //在这个方法中collectionView的大小已经确定
            let row: CGFloat = 3
            let col: CGFloat = 7
            let w = collectionView!.bounds.width / col
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            let lineMargin = (collectionView!.bounds.height - w * row) * 0.499
            sectionInset = UIEdgeInsets(top: lineMargin, left: 0, bottom: lineMargin, right: 0)
            scrollDirection = .Horizontal
            
            collectionView?.bounces = false
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false

        }
    }
}

// MARK: - 界面处理
private extension SYLJEmoticon { //加private后扩展中的函数都是私有的

    /// 设置界面
    func setupUI() {
        //添加控件
        toolbar.backgroundColor = UIColor.greenColor()
        addSubview(toolbar)
        addSubview(collectionView)
        //设置布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(36)
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        //添加子控件的内容
        prepareToolbar()
        prepareCollectionView()
    }
    /// collectionView的设置
    private func prepareCollectionView() {
        collectionView.backgroundColor = UIColor.lightGrayColor()
        // 注册 Cell
        collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: EmoticonViewCellId)
        // 指定数据源
        collectionView.dataSource = self
        // 设置代理
        collectionView.delegate = self
    }
    /// 准备工具栏
    private func prepareToolbar() {
        var items = [UIBarButtonItem]()
        var index = 0
        //对于功相近的对象的一半用tag值区分
        for s in packages {
            let item = UIBarButtonItem(title: s.group_name_cn, style: .Plain, target: self, action: "clickItem:")
            item.tag = index++
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
    }
    
}

// MARK: - UICollectionViewDataSource
extension SYLJEmoticon: UICollectionViewDataSource,UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticon = packages[indexPath.section].emoticons[indexPath.item]
        selectedEmoticonCallBack(emoticon: emoticon)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonViewCellId, forIndexPath: indexPath) as! EmoticonCell
//        cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.redColor() : UIColor.greenColor()
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.row]
        return cell
     }
}
//MARK: - 自定义Cell
private class EmoticonCell: UICollectionViewCell {

    ///模型数据
    var emoticon: Emoticon? {
        didSet {
            if emoticon!.isRemove {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }else {
                emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.pngPath), forState: .Normal)
            }
            emoticonButton.setTitle(emoticon?.emoji, forState: .Normal)
        }
    }
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 懒加载控件
    private lazy var emoticonButton: UIButton = UIButton()
    
    // MARK: - 设置界面
    private func setupUI() {
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
        emoticonButton.userInteractionEnabled = false
        //字体的大小和线宽是一致的
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        // 添加控件
        contentView.addSubview(emoticonButton)
        // 设置位置
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
    }
    
}
    